package com.niuwa.p2p.service.role.impl;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.axis2.databinding.types.soapencoding.Array;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.dao.role.RoleDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.role.Role;
import com.niuwa.p2p.service.role.RoleService;


public class RoleServiceImpl implements RoleService{
	@Autowired
	private RoleDao roleDao;
	
	@Override
	public JsonResult saveRole(Role role){
		JsonResult jsonResult=new JsonResult(false,"角色添加失败!");
		Integer obj = roleDao.saveRole(role);//影响行数
		if (obj>0) {
			jsonResult.setSuccess(true);
			jsonResult.setMsg("角色添加成功!");
		}
		return jsonResult;
	}

	@Override
	public JsonResult updateRole(Role role) {
		JsonResult jsonResult=new JsonResult(false,"角色修改失败!");
		Object obj = roleDao.updateRole(role);
		if (Integer.parseInt(obj.toString())>0) {
			jsonResult.setSuccess(true);
			jsonResult.setMsg("角色修改成功!");
		}
		return jsonResult;
	}

	
	

	/**
	 * 
	 * 分页查询
	 * paramMap 查询参数
	 */
	@Override
	public PageBean<Role> search(Map<String, Object> paramMap){
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		Map<String, Object> formatParamMap=formatDate(paramMap);
		//总条数
		int totalCount = roleDao.getRoleCountByCondition(formatParamMap);
		PageBean<Role> page = new PageBean<Role>(totalCount);
		// 当前页
		page.setPage(((PageQuery) formatParamMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(roleDao.getRoleByCondition(formatParamMap));
		return page;
	}

	@Override
	public Role getRoleById(long id) {
		return roleDao.getRoleById((int)id);
	}

	@Override
	public JsonResult checkRoleNameIsExists(String roleName){
		JsonResult jsonResult=new JsonResult(true);
		Object obj = roleDao.checkRoleNameIsExists(roleName);
		if (obj!=null) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg("角色名称已存在!");
		}
		return jsonResult;
	}
/**
	@Override
	public JsonResult deleteRoleById(long id) {
		JsonResult jsonResult=new JsonResult(false,"角色删除失败!");
		int result= roleDao.deleteRoleById(id);
		if (result>0) {
			jsonResult.setSuccess(true);
			jsonResult.setMsg("角色删除成功!");
		}
		return jsonResult;
	}*/
	@Override
	public JsonResult changeRoleStatus(Integer roleId) {
		JsonResult jsonResult=new JsonResult();
		List<Map<String,Object>> userRole=roleDao.searchUserRoleByRoleId(roleId);
		List<Map<String,Object>> roleResource=roleDao.searchRoleResourceByRoleId(roleId);
		if(userRole.size()!=0){
		       //roleDao.deleteUserRole(roleId);
		       jsonResult.setMsg("角色删除失败,该角色有用户关联!");
		       return jsonResult; 
		}
		if( roleResource.size()!=0){
		       roleDao. deleteRoleResource(roleId);
		}
			int result= roleDao.changeRoleStatus(roleId);
			if (result>0) {
			
				jsonResult.setMsg("角色删除成功!");
			}
		return jsonResult;
	}

	/*@Override
	public JsonResult editRole(Role role) {
		JsonResult jsonResult=new JsonResult(false,"操作失败!");
		try {
			if (null!=role && StringUtils.isNotBlank(role.getOper())) {
				switch (role.getOper()) {
				case AppConstants.OPER_ADD:
					role.setCreatorId(1);
					jsonResult= this.saveRole(role);
					break;
				case AppConstants.OPER_EDIT:
					jsonResult= this.updateRole(role);
					break;
				case AppConstants.OPER_DEL:
					role.setMenderId(new Long(1));//TODO  暂定
					jsonResult= this.changeRoleStatus(role);
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			//TODO 
		}
		return jsonResult;
	}*/
	
	
	/**
	 * 查询全部的角色
	 * @return
	 */
	public List<Role>  searchAllRoles(){
		return roleDao.searchAllRoles();
		
	}

	/**
	 * 
	 *根据用户名查询对应角色
	 *@param loginName
	 *@return List<Role>
	 *
	 */
	public List<Role> searchRolesByloginName(String loginName){
		
		return  roleDao.searchRolesByloginName( loginName);
		
	}

	@Override
	public JsonResult editRole(Role role) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void deleteRoleById(Integer roleId) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 判断角色名称是否已经存在
	 * @param role
	 * @return
	 */
	@Override
	public List<Role> searchRoleByName(Role role) {
		return roleDao.searchRoleByName(role.getRoleName());
	}

	
	/**
	 * 
	 * 新增角色
	 * @param role
	 */
	@Override
	public void addRole(Role role,Long userId) {
		Map<String,Object> roleParamMap=new HashMap<String,Object>();
		String roleName=role.getRoleName();
		Character status=role.getStatus();
		String description=role.getDescription();
		Date createTime =new Date();
		roleParamMap.put("userId",(int)((long)userId));
		roleParamMap.put("roleName",roleName);
		roleParamMap.put("status",status);
		roleParamMap.put("description",description);
		roleParamMap.put("createTime",createTime);
		roleParamMap.put("updateTime",createTime);
		roleDao.addRole(roleParamMap);	
	}

	
			/**
			 * 
			 *修改角色
			 * @param role
			 * @param userId
			 *
			 */
	@Override
	public void updateRole(Role role, Integer roleId) {
		Map<String, Object> roleParamMap = new HashMap<String, Object>();
		String roleName = role.getRoleName();
		Character roleStatus = role.getStatus();
		String roleDescription = role.getDescription();
		Date updateTime = new Date();
		roleParamMap.put("roleId", roleId);
		roleParamMap.put("roleName", roleName);
		roleParamMap.put("roleStatus", roleStatus);
		roleParamMap.put("roleDescription",  roleDescription);
		roleParamMap.put("updateTime", updateTime);
		roleDao.updateRole(roleParamMap);	
	
	}
	
	
	/**
	 * 
	 *格式化时间
	 * @param paramMap
	 * @return Map
	 *
	 */
		public Map<String, Object> formatDate(Map<String, Object> paramMap) {
			String dateFromat1 = "MM/dd/yyyy";
			String dateFromat2 = "yyyy-MM-dd HH:mm:ss";
			SimpleDateFormat sdf1 = new SimpleDateFormat(dateFromat1);
			SimpleDateFormat sdf2 = new SimpleDateFormat(dateFromat2);
			String beginTime = (String) paramMap.get("beginTime");
			String endTime = (String) paramMap.get("endTime");
			if ((beginTime != null )&&!("".equalsIgnoreCase(beginTime))) {
				try {
					Date beginTime2 = sdf1.parse(beginTime);
					String beginTime3 = sdf2.format(beginTime2);
					paramMap.put("beginTime", beginTime3);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if ((endTime != null)&&!("".equalsIgnoreCase(endTime)))
				try {
					Date endTime2 = sdf1.parse(endTime);
					String endTime3 = sdf2.format(endTime2);
					paramMap.put("endTime", endTime3);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return paramMap;
		}

		/**
		    * 
		    *为用户授予角色
		    * @param roleParamMap
		    *
		    */
	@Override
	public void updateUserRole(Integer userId,String[] roleIdArr) {
		Map<String,Object> userRoleMap=new HashMap<String, Object>();
		List<Integer> roleIdList=new ArrayList<Integer>();
		for(int i=0;i<roleIdArr.length;i++){
			roleIdList.add(Integer.parseInt(roleIdArr[i]));
		}
		roleDao.deleteUserRoleByUserId(userId); 
		userRoleMap.put("userId", userId);
		userRoleMap.put("roleIdList",roleIdList);
		roleDao.insertUserRole(userRoleMap);
		
	}
	
	}
